import hashlib
from random import *
from copy import *

import minimax

class AIAgentMinimax:
    def __init__(self, id, depth):
        self.id = id
        self.depth = depth
        self.history = []
        self.knownStates = {}
        self.winStates = []
        self.lossStates = []
        
    def addToHistory(self, b):
        hash = hashlib.sha1(b.board).hexdigest()
        if not hash in self.knownStates:
            self.knownStates[hash] = deepcopy(b)
        self.history.append(hash)
         
    def learnFromLatestGame(self):
        win = self.history[-1].checkWin()
        n = 0
        for b in reversed(self.history[:-1]):
            if b.checkWin()[0] != 0:
                break
            n = n + 1
            if win[0] == self.id:
                self.winStates.append(b)
            else:
                self.lossStates.append(b)
        if win[0] == self.id:
            print "Learned from %i winning states" % n
        else:
            print "Learned from %i losing states" % n
    
    def play(self, board):
        # Check if we can use history
        hash = hashlib.sha1(b.board).hexdigest()
        if
        self.addToHistory(board)
        board.currentPlayerValue = 1
        #action = minimax.alphabeta(board, 4)
        action = minimax.minimax(board, self.depth)
        if action[0] > -1000:
            bestAction = action[1]
        else:
            actions = board.notFullColumns()
            if actions == []:
                return
            bestAction = choice(actions)
        board.drop(bestAction, self.id)
        self.addToHistory(board)

    def printHistory(self):
        n = 0
        for b in self.history:
            print "State ", n, b
            print self.knownStates[b]
            n = n + 1